package com.wen.moudle;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.wen.config.Config;
import com.wen.config.DefaultPropertyConfig;
import com.wen.entry.Result;
import com.wen.entry.bean.Information;
import com.wen.moudle.Managers.InformationManager;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.net.HttpCookie;
import java.util.List;


// 用户模块，登录退出功能
@Slf4j
public class Account implements Serializable {
    public final String username;

    public String name;
    public int level;
    private final String password;
    private final Config config;


    // cookies 没必要序列化
    private transient List<HttpCookie> cookies;

    // 好的属性
    private DefaultPropertyConfig defaultPropertyConfig = new DefaultPropertyConfig();

    public DefaultPropertyConfig getDefaultPropertyConfig() {
        return defaultPropertyConfig;
    }

    public void setDefaultPropertyConfig(DefaultPropertyConfig defaultPropertyConfig) {
        this.defaultPropertyConfig = defaultPropertyConfig;
    }

    public Account(String username, String password) {
        this.username = username;
        this.password = password;
        this.config = new Config("/fight.properties");
    }


    // 登录
    public Result<String> login(){
        HttpResponse response = HttpRequest.post(config.get("登录"))
                .form("username", username)
                .form("password", password)
                .execute();
        Result<String> result = null;
        if (response.body() == null || response.body().length() == 0){
            // 无响应，登录成功
            this.cookies = response.getCookies();
            HttpRequest.post(response.header("Location")).cookie(cookies)
                    .execute();
            log.info("登录成功");

            // 把name和level保存起来
            Information information = new InformationManager(this).getInfo().getData();
            name = information.getName();
            level = information.getLevel();


            return new Result<>(true,"登录成功","");
        }else{
            result = JSONUtil.toBean(response.body(), new TypeReference<Result<String>>() {},false);
            System.out.println(result.getErrorMessage());
        }
        return result;
    }




    // 退出
    public Result<String> logout(){
        log.info("退出账号");
        HttpResponse response = HttpRequest.post(config.get("退出"))
                .cookie(cookies)
                .execute();
        return JSONUtil.toBean(response.body(), new TypeReference<Result<String>>() {},false);
    }

    public List<HttpCookie> getCookies() {
        return cookies;
    }

    public Config getConfig() {
        return config;
    }

}
